﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Text;
using System.IO;
using System.Xml;

/// <summary>
/// CreateHtml 的摘要说明
/// </summary>
public class CreateHtml
{
	public CreateHtml()
	{		
		// TODO: 在此处添加构造函数逻辑
        serverRootPath = HttpRuntime.AppDomainAppPath.ToString();
        connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        //connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        //    HttpContext.Current.Server.MapPath("~/App_Data/rss.mdb");加上System.Web命名空间，也取不到值，还是null
    }
    public void CreateHtmlAuto()
    {
        string command = "select top 1 HtmlKind,ExpiryTime,AddMinute,KindName,RecommendCount,KindRecommend,TopRecommendCount from CurrentHtml order by ExpiryTime";
        OleDbConnection con = new OleDbConnection(connection);
        OleDbCommand cmd = new OleDbCommand(command, con);
        con.Open();
        OleDbDataReader r = cmd.ExecuteReader();
        r.Read();

        string kind, expiry, addMinute, photoCount, recommendCount, kindName,kindRecommend,topRecommendCount;
        kind = r[0].ToString();
        expiry = r[1].ToString();
        addMinute = r[2].ToString();
        kindName = r[3].ToString();
       // photoCount = r[4].ToString();
        recommendCount = r[4].ToString();
        kindRecommend = r[5].ToString();
        topRecommendCount = r[6].ToString();

        con.Close();
        DateTime expiryTime = DateTime.Parse(expiry);
        if (expiryTime < DateTime.Now)
        {
            CreateHtmlByHand(kind, addMinute, recommendCount, kindName, kindRecommend, topRecommendCount);
        }
    }
    public void CreateHtmlByHand(string kind, string addMinute, string recommendCount, string kindName,string inKindRecommend, string topRecommendCount)//, string photoCount
    {
        StringBuilder sb = new StringBuilder();
        XmlDocument doc = new XmlDocument();
        doc.Load(serverRootPath + "/App_Data/HtmlKind.xml");
        XmlElement root = doc.DocumentElement;
        string head, title, cssJS,menuDiv,foot;                
        head = root.SelectSingleNode("htmlHead").InnerText;
        title = root.SelectSingleNode("pageTitle").SelectSingleNode(kind).InnerText;
        cssJS = root.SelectSingleNode("htmlCssJS").InnerText;        
        menuDiv = root.SelectSingleNode("htmlMenu").InnerText;
        foot = root.SelectSingleNode("htmlFoot").InnerText;        
        
        sb.Append(head + "<title>" + title + "</title>" + cssJS + menuDiv);

        string menuContent = "";//此处生成的顶部分类菜单，以后用js生成的实时菜单替代此菜单
        DateTime d = DateTime.Now;//生成最新的html名称。        
        string htmlFileName = "news";//d.Year.ToString() + "_" + d.Month.ToString() + "_" + d.Day.ToString();
        //使用总的iframe 菜单，不要新闻分类菜单了
        //menuContent = GetHeadMenuHtml(kind, htmlFileName);
        //sb.Append(menuContent + "</div><!--htmlNewsMenu--></div><!--menuBox-->"); //加上菜单htmlNewsMenu的div结束menuBox的结束标签
        sb.Append(menuContent + "</div><!--htmlNewsMenu--></div><!--menuBox-->");
        sb.Append("<div id='newsContainer'>");//添加新闻容器开始
        OleDbConnection con = new OleDbConnection(connection);//生成新闻目录子菜单
        OleDbCommand cmd = new OleDbCommand("select SiteId, SiteDesc from Sites where SiteKind='" + kind + "' and IsLatest=true order by SiteMenuOrder", con);
        con.Open();
        OleDbDataReader readkind = cmd.ExecuteReader();
        string siteContent = "";
        while (readkind.Read())
        {
            siteContent += readkind[0].ToString() + "," + readkind[1].ToString() + ";";
        }
        readkind.Close();
        siteContent = siteContent.Remove(siteContent.Length - 1, 1);       
        string[] sites = siteContent.Split(';');
        int n = 1;
        string[] siteCurrent = new string[2];
        foreach (string s in sites)
        {
            siteCurrent = s.Split(',');
            string id, desc;
            id = siteCurrent[0];desc = siteCurrent[1];
            try
            {
                OleDbDataReader read = GetNews(id);//一个新闻站点开始，s.Substring(0, s.IndexOf(','))                
                sb.Append("<div class='newsBlock'><div id='newsHead" + n.ToString() + "' class='headNews'>" + desc + "</div>");                
                sb.Append("<div id='newsNav" + n.ToString() + "' class='newsDiv'><ul>");
                while (read.Read())
                {   //haveNewsDetail:0没有获取内容,1获取内容，2获取失败
                    string myLink = read[3].ToString() == "1" ? "../newsDetail/" + read[4].ToString() + ".html" : read[0].ToString();
                    sb.Append("<li><a class='newstitle' href='" + myLink + "' target='_blank'>" +
                           read[1].ToString() + "</a> <span class='newsdate'>" + read[2].ToString() + "</span></li>");
                }
                read.Close();
                sb.Append("</ul></div></div><!--newsBlock-->");//一个新闻站点结束
                n++;
            }
            catch (OleDbException oex)
            { sb.Append("</ul></div></div>"); string aaaa = oex.Message; n++; }
        }
        sb.Append("</div><!--newsContainer-->");//newsContainer新闻容器结束
        
        sb.Append(foot + "</center></body></html>");               

        using (StreamWriter w = new StreamWriter(serverRootPath + "htmlNews\\" + kind + htmlFileName + ".html", false, System.Text.Encoding.UTF8))
        {
            w.Write(sb.ToString());
            w.Close();
        }
        //更新数据库记录，保存最新生成的html文件名,生成 js 菜单文件
        UpdateCurrentHtml(kind, kind + htmlFileName + ".html", addMinute);
        //WriteJsMenu(firstMenu);
    }
    protected void UpdateCurrentHtml(string kind, string htmlAddress, string addMinute)
    {
        DateTime d = DateTime.Now.AddMinutes(double.Parse(addMinute));
        string command = "UPDATE CurrentHtml SET HtmlAddress='" + htmlAddress + "', ExpiryTime='" + d.ToShortDateString() + " " +
            d.Hour.ToString() + ":" + d.Minute.ToString() + ":" + d.Second.ToString() + "' WHERE HtmlKind = '" + kind + "'";
        OleDbConnection con = new OleDbConnection(connection);
        OleDbCommand cmd = new OleDbCommand(command, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    //protected void WriteJsMenu(string menu)
    //{
    //    using (StreamWriter w = new StreamWriter(serverRootPath + "js\\headmenu.js", false, System.Text.Encoding.Default))
    //    {
    //        w.Write("document.write(\"" + menu + "\");");
    //        w.Close();
    //    }
    //}
    protected string GetHeadMenuHtml(string kind, string htmlFileName)
    {        
        StringBuilder sb = new StringBuilder();        
        sb.Append("<ul>");
        string command = "select HtmlKind, HtmlAddress, KindName from CurrentHtml where HtmlAddress is not null order by MenuOrder";
        OleDbConnection con = new OleDbConnection(connection);
        OleDbCommand cmd = new OleDbCommand(command, con);
        con.Open();
        OleDbDataReader r = cmd.ExecuteReader();
        while (r.Read())
        {
            if (r[0].ToString() == kind)//如果是本分类，用现在即将生成的最新文件名，生成菜单
            {
                sb.Append("<li><nobr><a href='" + kind + htmlFileName + ".html' class='currentMenu'>" + r[2].ToString() + "</a></nobr></li>");                
            }
            else
            {
                sb.Append("<li><nobr><a href='" + r[1].ToString() + "'>" + r[2].ToString() + "</a></nobr></li>");                
            }
        }
        r.Close();
        con.Close();
        sb.Append("<li><a href='http://www.toook.com'>首　页</a></li></ul>");  //      
        return sb.ToString();
    }
    /// <summary>
    /// 获取新闻link链接,title标题,pubDate日期,haveNewsDetail是否有内容,insertOrder编号
    /// </summary>
    /// <param name="siteId">新闻站点ID</param>
    /// <returns>DataReader结果集link,title,pubDate,haveNewsDetail,insertOrder</returns>
    protected OleDbDataReader GetNews(string siteId)
    {
        OleDbConnection con = new OleDbConnection(connection);
        OleDbCommand cmd = new OleDbCommand("SELECT [link],[title],[pubDate],[haveNewsDetail],[insertOrder] FROM [RssNews] WHERE [siteId] = " + siteId, con);
        con.Open();
        return cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
    //protected OleDbDataReader GetRecommendNews(string recommendKind, string recommendCount)
    //{
    //    string command = "SELECT top " + recommendCount + " [Link],[Title], [ImageUrl], [ImageCss] FROM [RecommendNews] WHERE [Kind] = '" + recommendKind + "'";
    //    OleDbConnection con = new OleDbConnection(connection);
    //    OleDbCommand cmd = new OleDbCommand(command, con);
    //    con.Open();
    //    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
    //}
    private string serverRootPath;
    private string connection;

}
